﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="BusquedaComerciosCercanos.aspx.cs" Inherits="Web_Guia_Digital_Georeferenciada.BusquedaComerciosCercanos" %>


<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type = "text/javascript"></script>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel = "Stylesheet" type="text/css" />
    <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
      <script src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry" type="text/javascript"></script>   
 
    <link rel="stylesheet" href="Content/bootstrap.min.css" type="text/css" /> 
    <script type="text/javascript" src="Content/bootstrap.min.js"></script> 
<script type ="text/javascript">
    // VARIABLES GLOBALES JAVASCRIPT
    var geocoder; var marker; var latLng; var latLng2; var map;
    var infowindow; var marcadores = []; var miPos;
    var markerInicial; var myRadius;
    var draw_circle = null;
    // INICiALIZACION DE MAPA
    function InitializeMap() {
        geocoder = new google.maps.Geocoder();
        latLng = new google.maps.LatLng(miPos.latitude, miPos.longitude);
        geocodePosition(latLng);
        map = new google.maps.Map(document.getElementById('map-canvas'), {
            zoom: 17,
            scrollwheel: false,
            navigationControl: false,
            mapTypeControl: false,
            scaleControl: false,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

        map.setCenter(latLng);
        
        var pinShadow = new google.maps.MarkerImage( '<%=ResolveUrl("~/Imagenes/markerPerson.png") %>',
            new google.maps.Size(150, 150),
            new google.maps.Point(0, 0),
            new google.maps.Point(12, 35));


        // CREACION DEL MARCADOR  
        markerInicial = new google.maps.Marker({
            position: latLng,
            title: 'usted esta aquí',
            map: map,
            draggable: false,
            icon: pinShadow,
        });


        Buscar();
        $("#search_radius").change(function () {
            Buscar();
        });
    }

    function updateMarkerAddress(str) {
        $('#txtDireccion').val(str);
    }
    function geocodePosition(pos) {
        geocoder.geocode({
            latLng: pos
        }, function (responses) {
            if (responses && responses.length > 0) {
                updateMarkerAddress(responses[0].formatted_address);
            } else {
                updateMarkerAddress('No puedo encontrar esta direccion.');
            }
        });
    }

    function ObtenerPosicion() {
        var options = {
            enableHighAccuracy: true,
            timeout: 45000
        };

        navigator.geolocation.getCurrentPosition(GetPosition, funcionError, options);

        function GetPosition(posicion) {
            miPos = posicion.coords;
            InitializeMap();
           
        }
        function funcionError(error) {
            alert(error.message);
        }
    }

   function Buscar() {
        $.ajax({
            type: "POST",
            url: '<%=ResolveUrl("~/Mantenimientos/ServiciosAutocompletado.asmx/BusquedaCercanos") %>',
            //  data: param,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                jQuery.each(data, function (index, item) {
                    ArmarMapa(item);
                });
            },
            error: SetTabSessionValueFailed
        });

    }
    function ArmarMapa(item) {
        var ltlng = [];
        for (var i = 0; i < marcadores.length; i++) {
            marcadores[i].setMap(null); //Remove the marker from the map
        }
        for (i = 0; i < item.length; i++) {
            ltlng.push(new google.maps.LatLng(item[i].Latitud, item[i].Longitud));
        }
       var contador = 0;
        for (var i = 0; i <= ltlng.length; i++) {
            if (calcDistance(markerInicial.getPosition(), ltlng[i]) < $('#search_radius').val() * 100) {
                contador++;
                marker = new google.maps.Marker({
                    map: map,
                    animation: google.maps.Animation.DROP,
                    position: ltlng[i]
                });
                (function (i, marker) {
                    //Aca armo info de los comercios
                    google.maps.event.addListener(marker, 'click', function () {
                        if (!infowindow) {
                            infowindow = new google.maps.InfoWindow();
                        }
                        infowindow.setContent("Nombre: " + item[i].ComercioNombre + "<br/> Dirección: " + item[i].ComercioDireccion + "<br/> Tel:" + item[i].ComercioTelefono);

                        infowindow.open(map, marker);
                    });

                })(i, marker);
                marcadores.push(marker);
            }
            if (contador > 0) {
                $("#result_count").text(contador + " comercio/s encontrado/s");
            }
            else {
                $("#result_count").text("No se encontraron resultados");

            }
        }
    }
    function SetTabSessionValueFailed() {
        alert('call failed');
    }
    function calcDistance(fromLatng, toLatng) {
        return google.maps.geometry.spherical.computeDistanceBetween(fromLatng, toLatng);
    }

</script>
<style type="text/css">
html,body{
  	height:100%;
}

body{
       /* background-image: url(Imagenes/fondo.jpg);*/
    background-repeat:no-repeat;
  	padding-top:50px; /*padding for navbar*/
    width:100%;
}
#main, #main>.row {
	height:100%;
}

#main>.row {
    overflow-y:scroll;
}

#left {
	height:100%;
}

#map-canvas {
    max-width: none;
	width:65%;
    height:550px;
    position:absolute;
    right:16px;
    top:125px;
    bottom:0;
    overflow:hidden;
}
#resultsList {
    max-width: none;
	width:65%;
    height:550px;
    position:absolute;
    right:16px;
    top:125px;
    bottom:0;
    overflow:hidden;
}

.filter-box { 
  height: 15px; 
  width: 15px;  
  display: inline-block;
  *border-right-width: 2px;
  *border-bottom-width: 2px;
  -webkit-border-radius: 5px;
     -moz-border-radius: 5px;
          border-radius: 5px;
  -webkit-background-clip: padding-box;
     -moz-background-clip: padding;
          background-clip: padding-box; 
}

.filter-yellow { background-color: #FBF358; }
.filter-green { background-color: #00E13C; }
.filter-blue { background-color: #5781FC; }
.filter-purple { background-color: #7C54FB; }
.filter-red { background-color: #FB6353; }

canvas {-ms-touch-action: double-tap-zoom;}

hr{border: 0; height: 12px; box-shadow: inset 0 12px 12px -12px blue;}



/* customize nav style */
.navbar-custom {
    background-color: #4b4b4b;
	font-weight:700;
    text-transform:uppercase;
    border-width:0;
}
.navbar-custom  .navbar-nav>li>a {
	color: #ddd;
}
.navbar-custom  .navbar-nav li>a:hover, .navbar-nav li .open, .navbar-custom .navbar-nav .active a  {
	background-color: #7e7e7e;
}
.navbar-custom .dropdown-menu{
	right:0;
}
.navbar-custom .navbar-nav>.dropdown>a .caret {
	border-top-color: #999;
	border-bottom-color: #999;
}

.navbar-collapse.in { /*3.0.2 bug workaround*/
    overflow-y: visible;
}

.navbar-toggle {
	outline:0;
}
    </style>
</head>
<body onload="ObtenerPosicion();">
    <!-- Static navbar -->
    <nav class="navbar navbar-custom navbar-fixed-top" id="nav">
      <div class="container">
        <div id="navbar" class="navbar-collapse collapse">
          <ul class="nav navbar-nav">
                <li ><a href="<%= Page.ResolveUrl("~/PaginaPrincipalBT.aspx") %>">Principal</a></li>
                <li><a href="<%= Page.ResolveUrl("~/BusquedaComerciosGeoreferenciado.aspx") %>">Posición</a></li>
                <li ><a href="<%= Page.ResolveUrl("~/BusquedaComercios.aspx") %>">Busqueda ampliada</a></li>
                <li class="active"><a href="<%= Page.ResolveUrl("~/BusquedaComerciosCercanos.aspx") %>">Cercanos</a></li>
          </ul>
          <ul class="nav navbar-nav navbar-right">
            <li><a href="<%= Page.ResolveUrl("~/Sesion.aspx") %>">Inicio Sesión</a></li>
          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </nav>
    <!-- Segundo header -->
        <div class="navbar navbar-default">
         <div class="navbar-header">
             <a class="navbar-brand">Filtrar por Nombre</a>
         </div>
        <div class="navbar-collapse collapse">
            <form class="navbar-form" >
                <div class="form-group" style="display:inline;">
                <div class="input-group">
                <input id="txtBusqueda" type="text" class="form-control" placeholder="Ingresa el nombre del comercio para filtrar el mapa/lista?" />
                <span class="input-group-addon"><span onclick="Buscar();" class="glyphicon glyphicon-search" aria-hidden="true" ></span> </span>
                </div>
                </div>
            </form>
        </div>
        </div>
<div id='listCanvas' style='display: none;'>
<div id='resultsList'></div>
    </div>
<div id="map-canvas"></div>
<div class="container-fluid" id="main">
  <div class="row">
  	 <div class='col-md-4'>
            <div class='well'>
            <h4>
             Seleccione los filtros de búsqueda.
            </h4>
          <br />
               <form id="Form1" runat="server">
                <label> Dirección: <input class='form-control' id='txtDireccion' type='text' style ="width: 300px; "/> </label>
               <label>
                <select class='input-small' id='search_radius'>
                <option value='2'>2 cuadras</option>
                <option value='5'>5 cuadras</option>
                <option value='10'>10 cuadras</option>
                <option value='20'>20 cuadras</option>
                </select>
                Radio.
               </label>
                   <input class='form-control' id='txtLongitud' type='text' style ="visibility: hidden; width: 300px; "/>
               
               </form>
             <a class='btn btn-primary' id='buscarFiltro' href='#'>
              <i class='glyphicon glyphicon-search'></i>
              Buscar
            </a>
            <a class='btn btn-default' id='reset' href='#'>
              <i class='glyphicon glyphicon-repeat'></i>
              Reset
            </a>
          </div>
          <div class='alert alert-info' id='result_box' ><strong id='result_count'></strong></div>
    </div>
    <div class="col-xs-4"><!--map-canvas will be postioned here--></div>
    
  </div>
</div>
</body>
</html>
